package br.com.mtg.movethegarbage.impl;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import br.com.mtg.movethegarbage.framework.Game;
import br.com.mtg.movethegarbage.framework.Input;
import br.com.mtg.movethegarbage.framework.GameKeyEvent;
import br.com.mtg.movethegarbage.framework.GameTouchEvent;

public class GameInput extends Input
{
	@Override
	public boolean onTouch(View view, MotionEvent e)
	{

		GameTouchEvent g = new GameTouchEvent(e, view);
		synchronized (this)
		{
			touchEvents.add(g);
		}
		return true;
	}

	@Override
	public boolean onKey(View view, int keyCode, KeyEvent e)
	{
		if (e.getAction() == KeyEvent.ACTION_MULTIPLE)
			return false;
		GameKeyEvent g = new GameKeyEvent(e);
		synchronized (this)
		{
			keyEvents.add(g);
			if (keyCode > 0 && keyCode < 128)
			{

				if (g.type == GameKeyEvent.KEY_DOWN)
					pressedKeys[keyCode] = true;
				else
					pressedKeys[keyCode] = false;
			}
			else if (g.keyCode == KeyEvent.KEYCODE_BACK)
				backPressed = true;
		}
		return true;
	}

	@Override
	public ArrayList<GameKeyEvent> getKeyEvents()
	{
		synchronized (this)
		{
			return keyEvents;
		}
	}

	@Override
	public ArrayList<GameTouchEvent> getTouchEvents()
	{
		synchronized (this)
		{
			return touchEvents;
		}
	}

	@Override
	public void onBackPressed()
	{
		synchronized (this)
		{
			backPressed = true;
		}
	}

	@Override
	public boolean wasBackPressed()
	{
		synchronized (this)
		{
			if (backPressed)
			{
				backPressed = false;
				return true;
			}
			// else
			return false;
		}
	}

	@Override
	public boolean[] getPressedKeys()
	{
		synchronized (this)
		{
			return pressedKeys;
		}
	}

	@Override
	public boolean isKeyPressed(int keyCode)
	{
		synchronized (this)
		{
			if (keyCode > 0 && keyCode < 128)
				return pressedKeys[keyCode];
			// else
			return false;
		}
	}

	@Override
	public void showKeyboard(Game game)
	{
		InputMethodManager inputMethod = (InputMethodManager) ((Activity) game).getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethod.showSoftInput(game.getGraphics().getView(), 0);
	}

	@Override
	public void hideKeyboard(Game game)
	{
		InputMethodManager inputMethod = (InputMethodManager) ((Activity) game).getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethod.hideSoftInputFromInputMethod(game.getGraphics().getView().getWindowToken(), 0);
	}
}
